from flask import request, current_app
from flask_restx import Resource, Namespace, fields
from flask_jwt_extended import get_jwt_identity
from app.services.user_profile_service import UserProfileService
from app.utils.auth import user_token_required
from app.utils.response import success_response, error_response
from app.utils.validators import validate_required_fields
from . import api

# 创建命名空间
profile_ns = Namespace('profile', description='用户资料管理')

# 定义请求模型
profile_update_model = profile_ns.model('ProfileUpdate', {
    'nickname': fields.String(description='昵称'),
    'real_name': fields.String(description='真实姓名'),
    'gender': fields.Integer(description='性别：1男2女'),
    'birthday': fields.String(description='生日 YYYY-MM-DD'),
    'height': fields.Integer(description='身高cm'),
    'weight': fields.Integer(description='体重kg'),
    'signature': fields.String(description='个性签名'),
    'province': fields.String(description='省份'),
    'city': fields.String(description='城市'),
    'district': fields.String(description='区县'),
    'address': fields.String(description='详细地址'),
    'profile': fields.Raw(description='详细资料信息', example={
        'education': '本科',
        'occupation': 'IT行业',
        'income_range': '10-20万',
        'marital_status': '未婚',
        'housing_status': '已购房',
        'car_status': '已购车',
        'smoking_habit': '不吸烟',
        'drinking_habit': '偶尔饮酒',
        'personality_traits': '["开朗", "幽默"]',
        'hobby_tags': '["读书", "旅行", "健身"]',
        'self_intro': '热爱生活，积极向上...'
    })
})

status_update_model = profile_ns.model('StatusUpdate', {
    'status': fields.Integer(required=True, description='状态：1正常2待审核3审核失败4封禁5注销')
})

profile_validation_model = profile_ns.model('ProfileValidation', {
    'profile_data': fields.Raw(required=True, description='待验证的资料数据')
})

@profile_ns.route('/profile')
class UserProfileAPI(Resource):
    """用户资料接口"""
    
    @user_token_required
    def get(self, current_user):
        """获取个人资料"""
        try:
            profile_data = UserProfileService.get_user_profile(current_user.id, for_public=False)
            if not profile_data:
                return error_response('用户资料不存在', 404)
            
            return success_response(profile_data, '获取成功')
        except Exception as e:
            current_app.logger.error(f"获取用户资料异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)
    
    @profile_ns.expect(profile_update_model)
    @user_token_required
    def put(self, current_user):
        """更新个人资料"""
        try:
            data = request.get_json() or {}
            
            # 更新用户资料（带验证）
            result = UserProfileService.update_user_profile(current_user.id, data)
            
            if not result['success']:
                return error_response(
                    result['error'], 
                    400, 
                    extra_data={
                        'validation_errors': result.get('validation_errors', []),
                        'warnings': result.get('warnings', [])
                    }
                )
            
            return success_response(
                result['data'], 
                result['message'],
                extra_data={
                    'updated_fields': result['updated_fields'],
                    'validation_warnings': result.get('validation_warnings', [])
                }
            )
        except Exception as e:
            current_app.logger.error(f"更新用户资料异常: {str(e)}")
            return error_response(f"更新失败: {str(e)}", 500)


@profile_ns.route('/users/<int:user_id>')
class UserDetailAPI(Resource):
    """用户详情接口"""
    
    @user_token_required
    def get(self, user_id, current_user):
        """获取用户详情"""
        try:
            user_data = UserProfileService.get_user_by_id(user_id, viewer_id=current_user.id)
            if not user_data:
                return error_response('用户不存在', 404)
            
            return success_response(user_data, '获取成功')
        except Exception as e:
            current_app.logger.error(f"获取用户详情异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


@profile_ns.route('/completeness')
class ProfileCompletenessAPI(Resource):
    """用户资料完整度分析接口"""
    
    @user_token_required
    def get(self, current_user):
        """获取用户资料完整度分析"""
        try:
            completeness_info = UserProfileService.get_completeness_analysis(current_user.id)
            
            if 'error' in completeness_info:
                return error_response(completeness_info['error'], 404)
            
            return success_response(completeness_info, '获取完整度分析成功')
        except Exception as e:
            current_app.logger.error(f"获取完整度分析异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


@profile_ns.route('/suggestions')
class ProfileSuggestionsAPI(Resource):
    """用户资料完善建议接口"""
    
    @user_token_required
    def get(self, current_user):
        """获取资料完善建议"""
        try:
            suggestions = UserProfileService.get_profile_suggestions(current_user.id)
            
            return success_response({
                'suggestions': suggestions,
                'total_count': len(suggestions)
            }, '获取建议成功')
        except Exception as e:
            current_app.logger.error(f"获取建议异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)


@profile_ns.route('/validate')
class ProfileValidationAPI(Resource):
    """用户资料验证接口"""
    
    @profile_ns.expect(profile_validation_model)
    @user_token_required
    def post(self, current_user):
        """验证资料数据"""
        try:
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['profile_data'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            profile_data = data.get('profile_data', {})
            
            # 执行验证
            validation_result = UserProfileService.validate_profile_data(profile_data)
            
            return success_response(validation_result, '验证完成')
        except Exception as e:
            current_app.logger.error(f"验证资料异常: {str(e)}")
            return error_response(f"验证失败: {str(e)}", 500)


@profile_ns.route('/status')
class UserStatusAPI(Resource):
    """用户状态管理接口"""
    
    @profile_ns.expect(status_update_model)
    @user_token_required
    def put(self, current_user):
        """更新用户状态"""
        try:
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['status'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            status = data.get('status')
            
            # 状态值验证
            if status not in [1, 2, 3, 4, 5]:
                return error_response('状态值无效', 400)
            
            # 某些状态用户不能自己设置
            if status in [4, 5] and current_user.id:  # 封禁和注销状态
                return error_response('无权限设置此状态', 403)
            
            updated_user = UserProfileService.update_user_status(current_user.id, status)
            if not updated_user:
                return error_response('更新失败', 400)
            
            return success_response(updated_user, '状态更新成功')
        except Exception as e:
            current_app.logger.error(f"更新用户状态异常: {str(e)}")
            return error_response(f"更新失败: {str(e)}", 500)


@profile_ns.route('/account')
class UserAccountAPI(Resource):
    """用户账户管理接口"""
    
    @user_token_required
    def delete(self, current_user):
        """注销账户"""
        try:
            success = UserProfileService.delete_user_account(current_user.id)
            if success:
                return success_response(message='账户注销成功')
            else:
                return error_response('注销失败', 400)
        except Exception as e:
            current_app.logger.error(f"注销账户异常: {str(e)}")
            return error_response(f"注销失败: {str(e)}", 500)


# 将命名空间注册到API实例
api.add_namespace(profile_ns) 